"use strict";
cc._RF.push(module, '02b62e5HLhM0IQH0kw8Wnri', 'GameLayoutController');
// scripts/game/GameLayoutController.ts

"use strict";
// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var GlobalBean_1 = require("../bean/GlobalBean");
var GamePlayerController_1 = require("../pfb/GamePlayerController");
var _a = cc._decorator, ccclass = _a.ccclass, property = _a.property;
var GameLayoutController = /** @class */ (function (_super) {
    __extends(GameLayoutController, _super);
    function GameLayoutController() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.Layout = null; // 分数布局容器
        _this.playerScorePfb = null; // player_score_pfb 预制体
        // 存储所有玩家控制器的映射
        _this.playerControllerMap = new Map();
        // 持久化记录：哪些用户已经死亡（用于断线/重连后仍需显示死亡图标）
        _this.deadUserIds = new Set();
        return _this;
        // update (dt) {}
    }
    // onLoad () {} 
    GameLayoutController.prototype.onLoad = function () {
        // 初始化时不自动创建界面，等待游戏数据
    };
    GameLayoutController.prototype.start = function () {
        // 不在start中自动创建，等待外部调用
    };
    /**
     * 清理分数显示界面
     */
    GameLayoutController.prototype.clearScoreView = function () {
        if (this.Layout) {
            this.Layout.removeAllChildren();
            // 清空玩家控制器映射
            this.playerControllerMap.clear();
            // 清空死亡记录
            this.deadUserIds.clear();
        }
    };
    /**
     * 创建分数显示界面
     * 支持砖块派对游戏和传统游戏两种数据格式
     */
    GameLayoutController.prototype.createScoreView = function () {
        // 检查必要的组件是否存在
        if (!this.Layout) {
            console.error("scoreLayout 未设置！请在编辑器中拖拽布局节点到 scoreLayout 属性");
            return;
        }
        if (!this.playerScorePfb) {
            console.error("playerScorePfb 未设置！请在编辑器中拖拽预制体到 playerScorePfb 属性");
            return;
        }
        // 清空现有的子节点，避免重复创建
        this.Layout.removeAllChildren();
        this.createBrickPartyView();
    };
    /**
     * 创建砖块派对游戏的界面
     */
    GameLayoutController.prototype.createBrickPartyView = function () {
        var gameStartData = GlobalBean_1.GlobalBean.GetInstance().noticeStartGame;
        var playerDataArray = gameStartData.users;
        // 根据playerNumber排序，确保按照1,2,3,4的顺序显示
        var sortedPlayerData = __spreadArrays(playerDataArray).sort(function (a, b) { return a.playerNumber - b.playerNumber; });
        // 根据后端playerData生成分数预制体
        for (var i = 0; i < sortedPlayerData.length; i++) {
            var playerData = sortedPlayerData[i];
            // 实例化预制体
            var item = cc.instantiate(this.playerScorePfb);
            this.Layout.addChild(item);
            // 获取预制体的控制器组件
            var playerController = item.getComponent(GamePlayerController_1.default);
            if (playerController) {
                // 创建兼容的RoomUser数据（用于显示基本信息）
                // 注意：砖块派对的数据结构直接包含这些字段
                var compatibleUser = {
                    userId: playerData.userId,
                    nickName: playerData.nickName || "Player" + playerData.playerNumber,
                    avatar: playerData.avatar || "",
                    pos: playerData.playerNumber,
                    coin: playerData.coin || 0,
                    status: playerData.bpStatus || 0,
                    score: 0,
                    rank: playerData.rank,
                    playerNumber: 0,
                    x: 0,
                    y: 0,
                    playerType: "",
                    surviveTime: 0
                };
                // 设置基本用户数据
                playerController.setData(compatibleUser);
                // 只设置playerTypeImage，不生成动物预制体（动物预制体由GamePageController统一管理）
                playerController.setPlayerTypeImageOnly(playerData.playerType);
                // 将控制器添加到映射中
                this.playerControllerMap.set(playerData.userId, playerController);
                // 若该玩家在进入时就已死亡（bpStatus == 2），记录并显示死亡图标
                if (playerData.bpStatus === 2) {
                    this.deadUserIds.add(playerData.userId);
                    playerController.showPlayerStatus(7);
                }
            }
            else {
                console.error("\u7B2C" + i + "\u4E2A\u9884\u5236\u4F53\u6CA1\u6709\u627E\u5230 GamePlayerController \u7EC4\u4EF6");
            }
        }
    };
    /**
     * 创建传统游戏的界面（保持原有逻辑）
     */
    GameLayoutController.prototype.createTraditionalView = function () {
        // 获取后端传回来的用户数据 - 使用原始顺序确保所有玩家看到相同的排列
        // 不再使用adjustUserData()方法，因为它会将当前玩家移到第一位，导致每个玩家看到不同的排列
        var users = GlobalBean_1.GlobalBean.GetInstance().noticeStartGame.users;
        // 使用基于房间ID的伪随机排列，确保所有玩家看到相同的排列顺序
        var seed = GlobalBean_1.GlobalBean.GetInstance().noticeStartGame.roomId;
        users = this.shuffleArrayWithSeed(users, seed);
        // 根据后端用户数据生成分数预制体
        for (var i = 0; i < users.length; i++) {
            var user = users[i];
            // 实例化预制体
            var item = cc.instantiate(this.playerScorePfb);
            this.Layout.addChild(item);
            // 获取预制体的控制器组件
            var playerController = item.getComponent(GamePlayerController_1.default);
            if (playerController) {
                // 设置用户数据到预制体
                playerController.setData(user);
                // 将控制器添加到映射中
                this.playerControllerMap.set(user.userId, playerController);
            }
            else {
                console.error("\u7B2C" + i + "\u4E2A\u9884\u5236\u4F53\u6CA1\u6709\u627E\u5230 GamePlayerController \u7EC4\u4EF6");
            }
        }
    };
    /**
     * 基于种子的伪随机数生成器（简单的线性同余生成器）
     */
    GameLayoutController.prototype.seededRandom = function (seed) {
        var current = seed;
        return function () {
            current = (current * 1664525 + 1013904223) % 4294967296;
            return current / 4294967296;
        };
    };
    /**
     * 使用种子随机打乱数组顺序，确保相同种子产生相同的排列结果
     */
    GameLayoutController.prototype.shuffleArrayWithSeed = function (array, seed) {
        var _a;
        var shuffled = __spreadArrays(array); // 创建副本，避免修改原数组
        var random = this.seededRandom(seed);
        for (var i = shuffled.length - 1; i > 0; i--) {
            var j = Math.floor(random() * (i + 1));
            _a = [shuffled[j], shuffled[i]], shuffled[i] = _a[0], shuffled[j] = _a[1];
        }
        return shuffled;
    };
    /**
     * 显示玩家状态（死亡、断线、退出、重连）
     * @param userId 用户ID
     * @param eventType 事件类型 (7-死亡, 8-断线, 9-退出, 10-重连)
     */
    GameLayoutController.prototype.showPlayerStatus = function (userId, eventType) {
        // 按事件维护死亡持久化记录
        if (eventType === 7) { // 死亡
            this.deadUserIds.add(userId);
        }
        else if (eventType === 9) { // 退出
            // 退出后也认为不再需要显示死亡状态（可按需求调整）
            this.deadUserIds.delete(userId);
        }
        var playerController = this.playerControllerMap.get(userId);
        if (playerController) {
            playerController.showPlayerStatus(eventType);
            // 特殊处理：重连(10)事件应当保留死亡图标
            if (eventType === 10 && this.deadUserIds.has(userId)) {
                playerController.showPlayerStatus(7);
            }
        }
        else {
            console.warn("\u672A\u627E\u5230\u7528\u6237 " + userId + " \u7684\u73A9\u5BB6\u63A7\u5236\u5668");
        }
    };
    /**
     * 根据OnlineStateEvent显示玩家状态（用于断线重连）
     * @param userId 用户ID
     * @param onlineStateEvent OnlineStateEvent值
     */
    GameLayoutController.prototype.showPlayerStatusByOnlineStateEvent = function (userId, onlineStateEvent) {
        var playerController = this.playerControllerMap.get(userId);
        if (playerController) {
            playerController.showStatusByOnlineStateEvent(onlineStateEvent);
        }
        else {
            console.warn("\u672A\u627E\u5230\u7528\u6237 " + userId + " \u7684\u73A9\u5BB6\u63A7\u5236\u5668");
        }
    };
    /**
     * 处理断线重连时的用户数据
     * @param users 用户数据数组
     */
    GameLayoutController.prototype.handleReconnectionUserData = function (users) {
        if (!users || users.length === 0) {
            console.warn("用户数据为空，无法更新玩家状态");
            return;
        }
        for (var _i = 0, users_1 = users; _i < users_1.length; _i++) {
            var user = users_1[_i];
            // 兼容大小写不同的字段名
            var onlineStateEvent = user.onlineStateEvent || user.OnlineStateEvent;
            if (user.userId && typeof onlineStateEvent === 'number') {
                // 同步死亡标记（2=死亡/淘汰）
                if (user.bpStatus === 2) {
                    this.deadUserIds.add(user.userId);
                }
                // 优先级：退出(9) > 离线(8) > 死亡(bpStatus=2) > 在线(10)
                var controller = this.playerControllerMap.get(user.userId);
                if (!controller) {
                    console.warn("\u672A\u627E\u5230\u7528\u6237 " + user.userId + " \u7684\u73A9\u5BB6\u63A7\u5236\u5668");
                    continue;
                }
                if (onlineStateEvent === 9) {
                    // 退出时优先级最高，且不再显示死亡
                    this.deadUserIds.delete(user.userId);
                    controller.showPlayerStatus(9);
                    continue;
                }
                if (onlineStateEvent === 8) {
                    // 离线优先于死亡显示
                    controller.showPlayerStatus(8);
                    continue;
                }
                if (this.deadUserIds.has(user.userId)) {
                    // 已死亡：仅在在线(10)时显示死亡
                    controller.showPlayerStatus(7);
                    continue;
                }
                // 其余情况按在线状态显示（断线/在线）
                controller.showStatusByOnlineStateEvent(onlineStateEvent);
            }
            else {
                console.warn("\u7528\u6237\u6570\u636E\u4E0D\u5B8C\u6574: userId=" + user.userId + ", onlineStateEvent=" + onlineStateEvent);
            }
        }
    };
    /**
     * 隐藏指定玩家的断线状态
     * @param userId 用户ID
     */
    GameLayoutController.prototype.hideDisconnectStatus = function (userId) {
        var playerController = this.playerControllerMap.get(userId);
        if (playerController) {
            playerController.hideDisconnectStatus();
        }
        else {
            console.warn("\u672A\u627E\u5230\u7528\u6237 " + userId + " \u7684\u73A9\u5BB6\u63A7\u5236\u5668");
        }
    };
    /**
     * 隐藏指定玩家的所有状态标识（死亡、断线、退出）
     * @param userId 用户ID
     */
    GameLayoutController.prototype.hideAllPlayerStatus = function (userId) {
        var playerController = this.playerControllerMap.get(userId);
        if (playerController) {
            playerController.hideAllStatusNodes();
            // 从死亡记录中移除（因为玩家重连且存活）
            this.deadUserIds.delete(userId);
        }
        else {
            console.warn("\u672A\u627E\u5230\u7528\u6237 " + userId + " \u7684\u73A9\u5BB6\u63A7\u5236\u5668");
        }
    };
    /**
     * 调试方法：列出所有玩家控制器
     */
    GameLayoutController.prototype.debugPlayerControllers = function () {
    };
    __decorate([
        property(cc.Node)
    ], GameLayoutController.prototype, "Layout", void 0);
    __decorate([
        property(cc.Prefab)
    ], GameLayoutController.prototype, "playerScorePfb", void 0);
    GameLayoutController = __decorate([
        ccclass
    ], GameLayoutController);
    return GameLayoutController;
}(cc.Component));
exports.default = GameLayoutController;

cc._RF.pop();